<script setup lang="ts">
import { ref, defineProps, watch, onMounted } from "vue";
import * as echarts from "echarts";
const props = defineProps({
  options: {
    type: Object,
    required: true,
    default: () => {},
  },
});
// 定义图表dom
const chartDom = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;
onMounted(() => {
  // 如果option 有数据，则初始化图表
  initChart();
});

function initChart() {
  if (chart) {
    // 如果图表有数据 先清空
    chart.clear();
    // 同时移除resize事件
    window.removeEventListener("resize", chart.resize);
  }
  //   判断 option 是否为空 如果为空 就不渲染了
  if (!props.options) {
    return;
  }

  chart = echarts.init(chartDom.value);
  chart.setOption(props.options);
  window.addEventListener("resize", chart.resize);
}
watch(
  () => props.options,
  (newVal, oldVal) => {
    // 说明option发生变化了
    initChart();
  }
);
</script>
<template>
  <div class="echartsEle" ref="chartDom"></div>
</template>
<style scoped>
.echartsEle {
  width: 100%;
  height: 100%;
}
</style>
